#include "bottomwidget.h"

BottomWidget::BottomWidget(QWidget *parent)
    : QWidget{parent}
{
    player=new QMediaPlayer(this);
    audiooutput=new QAudioOutput(this);
    rbtn=new RotatingButton(this);
    movinglabel=new MovingLabelWidget(this);
    slider=new MusicSliderWidget(this);
    volume=new VolumeWidget(this);
    mainlayout=new QHBoxLayout(this);
    vlayout=new QVBoxLayout;
    hlayout=new QHBoxLayout;
    for(int i=0;i<7;i++)
        buttons.push_back(new QPushButton(this));

    mainlayout->addWidget(rbtn);
    mainlayout->addLayout(vlayout);
    vlayout->addWidget(movinglabel);
    vlayout->addLayout(hlayout);
    for(int i=0;i<4;i++){
        hlayout->addWidget(buttons[i]);
        buttons[i]->hide();
    }

    movinglabel->setFixedSize(100,50);
    mainlayout->addStretch(1);
    mainlayout->addWidget(slider);
    mainlayout->addStretch(1);
    for(int i=4;i<7;i++)
        mainlayout->addWidget(buttons[i]);

    // buttons[0]->setIcon(QIcon(""));
    // buttons[1]->setIcon(QIcon(""));
    // buttons[2]->setIcon(QIcon(""));
    // buttons[3]->setIcon(QIcon(""));
    //buttons[4]->setIcon(QIcon(""));
    buttons[4]->hide();
    buttons[5]->setIcon(QIcon(":/icon/volumeHigh.png"));
    buttons[6]->setIcon(QIcon(":/icon/playlist.png"));

    volume->close();
    connect(volume,&VolumeWidget::volumeChange,this,&BottomWidget::SetVolume);
    volume->SetVolume(20);

    movinglabel->setFixedWidth(150);
    movinglabel->SetSongNameFont(QFont("",12));
    movinglabel->SetSongerFont(QFont("",10));
    connect(movinglabel,&MovingLabelWidget::clickLabel,this,[this](const QString&str){emit searchSignal(str);});

    connect(slider,&MusicSliderWidget::clickPause,this,&BottomWidget::pause);
    connect(slider,&MusicSliderWidget::clickPlay,this,&BottomWidget::play);
    connect(slider,&MusicSliderWidget::clickLast,this,[this]{
        emit previousSignal();
    });
    connect(slider,&MusicSliderWidget::clickNext,this,[this]{
        emit nextSignal();
    });

    player->setAudioOutput(audiooutput);
    connect(player, &QMediaPlayer::mediaStatusChanged, this,&BottomWidget::onMediaStatusChanged);
    connect(player,&QMediaPlayer::positionChanged,this,&BottomWidget::onPositionChanged);
    connect(player,&QMediaPlayer::durationChanged,this,&BottomWidget::onDurationChanged);
    connect(player,&QMediaPlayer::metaDataChanged,this,&BottomWidget::onMetaDataChanged);

    setAttribute(Qt::WA_Hover); // 启用悬浮事件
    resize(parent->width(),75);
    setGeometry(0,parent->size().height()-75,size().width(),size().height());

}

void BottomWidget::onMainWindowResize(const QSize& size)
{
    setGeometry(0,size.height()-75,size.width(),75);
}

void BottomWidget::onPlaySignal(const QUrl&url)
{
    SetPlayStream(url);
}

void BottomWidget::paintEvent(QPaintEvent*e)
{
    Q_UNUSED(e)
    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing);
    painter.setBrush(QColor("#fafafa")); // 背景颜色
    painter.setPen(Qt::NoPen); // 无边框
    painter.drawRoundedRect(rect(), 10, 10);
    // 覆盖下面两个角为方形(这里rect().top()-1是为了能覆盖住下面的边框，不减1无法覆盖会有曲线出现)
    QRect bottomRect(rect().left(), rect().top()-1, rect().width(), rect().height()/2);
    painter.drawRect(bottomRect);
}

void BottomWidget::mousePressEvent(QMouseEvent* e)
{
    QWidget::mousePressEvent(e);
    if(e->pos().x()>=width()-20&&e->pos().y()>=height()-20)
    {
        isdrag=true;
        startpoint=e->globalPosition().toPoint();
    }
}

void BottomWidget::mouseReleaseEvent(QMouseEvent* e)
{
    QWidget::mouseReleaseEvent(e);
    if(isdrag)
    {
        QPoint point=e->globalPosition().toPoint();
        QSize newsize;
        newsize.setWidth(parentWidget()->width()+point.x()-startpoint.x());
        newsize.setHeight(parentWidget()->height()+point.y()-startpoint.y());
        startpoint=point;
        emit newMainWindowSize(newsize);
    }
    isdrag=false;
}

void BottomWidget::mouseMoveEvent(QMouseEvent* e)
{
    QWidget::mouseMoveEvent(e);
    time=(time+1)%32;
    if(isdrag&&time==0)
    {
        QSize newsize;
        QPoint point=e->globalPosition().toPoint();
        newsize.setWidth(parentWidget()->width()+point.x()-startpoint.x());
        newsize.setHeight(parentWidget()->height()+point.y()-startpoint.y());
        startpoint=point;
        emit newMainWindowSize(newsize);
    }
}

bool BottomWidget::event(QEvent *e)
{
    if(e->type()==QEvent::HoverMove)
    {
        auto mousee=static_cast<QMouseEvent*>(e);
        if(mousee->pos().x()>=width()-20&&mousee->pos().y()>=height()-20)
        {
            setCursor(Qt::SizeFDiagCursor);
        }
        else
        {
            setCursor(Qt::ArrowCursor);
        }
        auto leftx=buttons[5]->pos().x();
        auto rightx=leftx+buttons[5]->width();
        auto topy=buttons[5]->pos().y();
        auto belowy=topy+buttons[5]->height();
        auto x=mousee->pos().x(),y=mousee->pos().y();
        if(leftx<=x&&x<=rightx&&topy<=y&&y<=belowy)
        {
            auto gpos=mapToGlobal(buttons[5]->pos());
            auto gx=gpos.x()+buttons[5]->width()/2-volume->width()/2;
            auto gy=gpos.y()-volume->height();
            volume->setGeometry(gx,gy,volume->width(),volume->height());
            volume->show();
        }
        else
            volume->close();

    }
    return QWidget::event(e);
}

void BottomWidget::onPositionChanged(qint64 position)
{
    qint32 tmp=position/1000;
    if(lastposition!=tmp)
    {
        qDebug()<<tmp;
        slider->SetPlayTime(tmp);
        lastposition=tmp;
    }
}

void BottomWidget::onDurationChanged(qint64 duration)
{
    qDebug()<<"play duration:"<<duration/1000;
    slider->SetTime(duration/1000);
}

void BottomWidget::onMediaStatusChanged(QMediaPlayer::MediaStatus status)
{
    switch (status)
    {
    case QMediaPlayer::LoadingMedia:
        qDebug() << "loading media...";
        break;
    case QMediaPlayer::BufferedMedia:
        qDebug() << "buffering is done，可以流畅播放";
        break;
    case QMediaPlayer::StalledMedia:
        qDebug() << "insufficient buffering，播放可能卡顿";
        break;
    case QMediaPlayer::EndOfMedia:
        qDebug() << "end of play";
        emit endSignal();
        break;
    default:
        //qDebug()<<"MediaStatus:"<<status;
        break;
    }
}

void BottomWidget::onMetaDataChanged()
{
    auto metadata=player->metaData();
    auto hashdata=metadata.asKeyValueRange();
    for(const auto& elem:hashdata)
    {
        qDebug()<<elem;
    }
    movinglabel->SetSongInfo(metadata[QMediaMetaData::Title].value<QString>(),metadata[QMediaMetaData::ContributingArtist].value<QStringList>());
    rbtn->SetImage(metadata[QMediaMetaData::ThumbnailImage].value<QImage>());//专辑图片
}
